package com.training.admin.web.controller.project;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.persistence.support.QueryFilter;
import com.demo2do.core.visitor.ObjectVisitor;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.training.admin.dao.ProjectTraineeDao;
import com.training.admin.entity.project.Project;
import com.training.admin.entity.project.ProjectPhase;
import com.training.admin.entity.project.ProjectPhaseCourse;
import com.training.admin.entity.project.ProjectTrainee;
import com.training.admin.entity.project.SurveyNotifaction;
import com.training.admin.entity.project.SurveyQuestion;
import com.training.admin.entity.project.TrainingSurvey;
import com.training.admin.entity.project.TrainingSurveyResult;
import com.training.admin.entity.trainee.Trainee;
import com.training.admin.service.DataService;
import com.training.admin.service.ProjectDataService;
import com.training.admin.service.ProjectPhaseCourseService;
import com.training.admin.service.ProjectPhaseService;
import com.training.admin.service.ProjectTraineeService;
import com.training.admin.service.TraineeService;
import com.training.admin.service.TrainingSurveyResultService;
import com.training.admin.service.TrainingSurveyService;
/**
 * 
 * @author sjh
 *
 */
@Controller
@RequestMapping("/project-results")
@MenuSetting("menu-training-project")
public class ProjectTraineeSurveryController {
	
	private static final Logger logger = LoggerFactory.getLogger(ProjectResultController.class);


	@Autowired
	private ObjectVisitor objectVisitor;

	@Dao
	private ProjectTraineeDao projectTraineeDao;


	@Autowired
	private ProjectDataService projectDataService;
	
	@Autowired
	private ProjectPhaseService projectPhaseService;
	
	@Autowired
	private ProjectPhaseCourseService projectPhaseCourseService;
	
	@Autowired
	private ProjectTraineeService projectTraineeService;
	
	@Autowired
	private TraineeService traineeService;
	
	@Autowired
	private TrainingSurveyResultService trainingSurveyResultService;

	@Autowired
	private TrainingSurveyService trainingSurveyService;
	
	@Autowired
	@Qualifier("dataService")
	private DataService<SurveyNotifaction> surveyNotifactionService; 
	
	
	/**
	 * 问卷生成、发送
	 * 
	 * @param projectPhaseId
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/{projectPhaseId}/trainee-survey-generate", method = RequestMethod.GET)
	@MenuSetting("submenu-project-result-management")
	public ModelAndView surveyGenerate(@PathVariable("projectPhaseId") Long projectPhaseId, Page page) {
		
		ModelAndView modelAndView = new ModelAndView("project-result/project-result-survey-generate");
	
		ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
		// get trainee list
		List<ProjectTrainee> projectTraineeList = projectTraineeService.listByProjectId(projectPhase.getProject().getId());
		
		int surveyCount = 0;
		
		for (int i = 0; i < projectTraineeList.size(); i++) {
			
			ProjectTrainee projectTrainee = projectTraineeList.get(i);
			TrainingSurvey trainingSurvey = new TrainingSurvey();
			trainingSurvey.setProjectPhase(projectPhase);
			trainingSurvey.setTrainee(projectTrainee.getTrainee());
			int checkCount = trainingSurveyService.count(TrainingSurvey.class, new QueryFilter().addEquals("projectPhase.id", projectPhase.getId()).addEquals("trainee.id", projectTrainee.getTrainee().getId()));
			
			SurveyNotifaction surveyNotifaction = new SurveyNotifaction(projectPhase, projectTrainee.getTrainee());
			if (checkCount == 0) {
				
				trainingSurveyService.save(trainingSurvey);
			
				surveyNotifactionService.save(surveyNotifaction);
				surveyCount++;
				
			}
		}

		modelAndView.addObject("projectPhase", projectPhase);
		modelAndView.addObject("traineeCount", surveyCount);
		return modelAndView;
	}
	
	/**
	 * 问卷调查
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/{projectPhaseId}/{traineeId}/survey", method = RequestMethod.GET)
	@MenuSetting("submenu-project-result-management")
	public ModelAndView survey(@PathVariable("projectPhaseId") Long projectPhaseId,
			@PathVariable("traineeId") Long traineeId) {
		ModelAndView modelAndView = new ModelAndView("project-result/project-result-survey");
		// get project Phase
		ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
		// get project phase courses
		List<ProjectPhaseCourse> projectPhaseCourseList = projectPhaseCourseService.listByProjectPhaseId(projectPhaseId);
		// get Trainee
		Trainee trainee = traineeService.load(Trainee.class, traineeId);

		List<SurveyQuestion> surveyList = (List<SurveyQuestion>) objectVisitor.evaluate("secure.surveys");
		List<SurveyQuestion> projectPhaseSurveys = new ArrayList<SurveyQuestion>();
		List<SurveyQuestion> courseSurveys = new ArrayList<SurveyQuestion>();
		
		for (int i = 0; i < surveyList.size(); i++) {
			
			SurveyQuestion surveyQuestion = surveyList.get(i);
		
			if ("phase".equals(surveyQuestion.getLevel())) {
			
				projectPhaseSurveys.add(surveyQuestion);
			} else {
				courseSurveys.add(surveyQuestion);
			}
		}
//        Map<String, List<String>> resources = (Map<String, List<String>>) objectVisitor.evaluate("");
		modelAndView.addObject("projectPhase", projectPhase);
		modelAndView.addObject("projectPhaseCourses", projectPhaseCourseList);
		modelAndView.addObject("trainee", trainee);
		modelAndView.addObject("projectPhaseSurveys", projectPhaseSurveys);
		modelAndView.addObject("courseSurveys", courseSurveys);

		return modelAndView;
	}
	
	
	/**
	 * 问卷结果提交
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/{projectPhaseId}/{traineeId}/survey", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@MenuSetting("submenu-project-result-management")
	public @ResponseBody HttpResult onSurvey(@PathVariable("projectPhaseId") Long projectPhaseId,
			@PathVariable("traineeId") Long traineeId, @RequestParam String[] surveyItem) {

		HttpResult httpResult = new HttpResult();
		try {
			// get project Phase
			ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
			// get project phase courses
			List<ProjectPhaseCourse> projectPhaseCourseList = projectPhaseCourseService.listByProjectPhaseId(projectPhaseId);
			// get Trainee
			Trainee trainee = traineeService.load(Trainee.class, traineeId);
			// get training survey
			List<TrainingSurvey> trainingSurveys = trainingSurveyService.list(new QueryFilter().addEquals("projectPhase.id", projectPhaseId).addEquals("trainee.id", traineeId));
			TrainingSurvey trainingSurvey = new TrainingSurvey();
			
			if (trainingSurveys == null || trainingSurveys.size() == 0) {
				
				trainingSurvey.setProjectPhase(projectPhase);
				trainingSurvey.setTrainee(trainee);
				// trainingSurveyService.save(trainingSurvey);
			} else {
				trainingSurvey = trainingSurveys.get(0);
			
				if (trainingSurvey.getStatus() != null && trainingSurvey.getStatus().equals("已提交")) {
				
					httpResult.fail("500").message("录入失败! ");
					logger.error("#onInputResult() - create project fail, exception is [{}]");
					return httpResult;
				}
			}

			List<SurveyQuestion> surveyList = (List<SurveyQuestion>) objectVisitor.evaluate("secure.surveys");
			List<SurveyQuestion> projectPhaseSurveys = new ArrayList<SurveyQuestion>();
			List<SurveyQuestion> courseSurveys = new ArrayList<SurveyQuestion>();
			for (int i = 0; i < surveyList.size(); i++) {
				
				SurveyQuestion surveyQuestion = surveyList.get(i);
				
				if ("phase".equals(surveyQuestion.getLevel())) {
				
						projectPhaseSurveys.add(surveyQuestion);
				} else {
					courseSurveys.add(surveyQuestion);
			}
			}

			int index = 0;
			// loop course
			for (int ii = 0; ii < projectPhaseCourseList.size(); ii++) {
				
				ProjectPhaseCourse projectPhaseCourse = projectPhaseCourseList.get(ii);
				// loop course questions
				for (int i = 0; i < courseSurveys.size(); i++) {
					
					SurveyQuestion courseSurvey = courseSurveys.get(i);
					TrainingSurveyResult trainingSurveyResult = new TrainingSurveyResult();
					trainingSurveyResult.setTrainee(trainee);
					trainingSurveyResult.setProjectPhase(projectPhase);
					trainingSurveyResult.setProjectPhaseCourse(projectPhaseCourse);
					trainingSurveyResult.setQuestion(courseSurvey.getQuestion());
					trainingSurveyResult.setInputValue(surveyItem[index]);

					trainingSurveyResultService.save(trainingSurveyResult);
					index++;
				}
			}
			// loop project phase questions
			for (int i = 0; i < projectPhaseSurveys.size(); i++) {
				
				SurveyQuestion projectPhaseSurvey = projectPhaseSurveys.get(i);
				TrainingSurveyResult trainingSurveyResult = new TrainingSurveyResult();
				trainingSurveyResult.setTrainee(trainee);
				trainingSurveyResult.setProjectPhase(projectPhase);
				// trainingSurveyResult.setProjectPhaseCourse(projectPhaseCourse);
				trainingSurveyResult.setQuestion(projectPhaseSurvey.getQuestion());
				trainingSurveyResult.setInputValue(surveyItem[index]);

				trainingSurveyResultService.save(trainingSurveyResult);
				index++;
			}

			trainingSurvey.setStatus("已提交");
			if (trainingSurvey.getId() == null) {
				trainingSurveyService.save(trainingSurvey);
			} else {
				trainingSurveyService.update(trainingSurvey);
			}

			httpResult.success().message("录入成功");

		} catch (Exception e) {
			httpResult.fail("500").message("录入失败! " + e.getMessage());
			logger.error("#onInputResult() - create project fail, exception is [{}]", e);
		}

		return httpResult;

	}
	
	/**
	 * 问卷调查-public
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "/{id}/survey", method = RequestMethod.GET)
	@MenuSetting("submenu-project-result-management")
	public ModelAndView survey(@PathVariable("id") Long id) {
		ModelAndView modelAndView = new ModelAndView("project-result/project-result-survey");
		// load traing survey
		@SuppressWarnings("unused")
        Project p = projectDataService.load(Project.class, new Long(3));
		TrainingSurvey trainingSurvey = trainingSurveyService.load(TrainingSurvey.class, id);
		try {
			if (trainingSurvey != null && trainingSurvey.getId() != null) {

				// get project Phase
				ProjectPhase projectPhase = trainingSurvey.getProjectPhase();
				// get project phase courses
				List<ProjectPhaseCourse> projectPhaseCourseList = projectPhaseCourseService.listByProjectPhaseId(projectPhase.getId());
				// get Trainee
				Trainee trainee = trainingSurvey.getTrainee();

				List<SurveyQuestion> surveyList = (List<SurveyQuestion>) objectVisitor.evaluate("secure.surveys");
				List<SurveyQuestion> projectPhaseSurveys = new ArrayList<SurveyQuestion>();
				List<SurveyQuestion> courseSurveys = new ArrayList<SurveyQuestion>();
				
				for (int i = 0; i < surveyList.size(); i++) {
				
					SurveyQuestion surveyQuestion = surveyList.get(i);
					
					if ("phase".equals(surveyQuestion.getLevel())) {
						projectPhaseSurveys.add(surveyQuestion);
					} else {
						courseSurveys.add(surveyQuestion);
					}
				}
				
				modelAndView.addObject("projectPhase", projectPhase);
				modelAndView.addObject("projectPhaseCourses", projectPhaseCourseList);
				modelAndView.addObject("trainee", trainee);
				modelAndView.addObject("projectPhaseSurveys", projectPhaseSurveys);
				modelAndView.addObject("courseSurveys", courseSurveys);
			} else {
				
				modelAndView.addObject("noData", true);
			}
		} catch (Exception exx) {
			
			modelAndView.addObject("noData", true);
		}

		return modelAndView;
	}


	
	
	
	/**
	 * 问卷结果
	 * 
	 * @param projectPhaseId
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/{projectPhaseId}/trainee-survey-list", method = RequestMethod.GET)
	@MenuSetting("submenu-project-result-management")
	public ModelAndView surveyTrainee(@PathVariable("projectPhaseId") Long projectPhaseId, Page page) {
		
		ModelAndView modelAndView = new ModelAndView("project-result/project-result-survey-trainee-list");
		
		ProjectPhase projectPhase = projectPhaseService.load(ProjectPhase.class, projectPhaseId);
		
		// get trainee list
		
		List<ProjectTrainee> projectTraineeList = projectTraineeService.listByProjectId(projectPhase.getProject().getId());
		
		modelAndView.addObject("projectPhase", projectPhase);
		modelAndView.addObject("projectTrainees", projectTraineeList);
		return modelAndView;
	}

	


}
